package com.itheima.controller;

import com.itheima.pojo.User;
import com.itheima.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Enumeration;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/comment")
@Slf4j
@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
// @CrossOrigin(allowCredentials = "false", allowedHeaders = "*") // 解决CSRF, 跨域禁止Cookie
public class CommentController {
    @Autowired
    private CommentService evaluateService;

    @PostMapping("/add")
    @ResponseBody
    public void add(@RequestBody Map<String, String> params, HttpServletRequest request){
        System.out.println("提交的数据: " + params);

       /*Enumeration<String> names = request.getHeaderNames();
        while (names.hasMoreElements()) {
            String header = names.nextElement();
            String value = request.getHeader(header);
            System.out.println(header + " :: " + value);
        }*/

        // 使用Referer解决CSRF
        String referer = request.getHeader("referer");
        if (referer == null || (!referer.startsWith("http://localhost:8080") && !referer.startsWith("https://localhost:8080"))) {
            log.error("referer不对, 被CSRF攻击了! 解决CSRF!");
            return;
        }

        // 获取提交的数据
        int iid = Integer.parseInt(params.get("iid"));
        String content = params.get("content");

        int uid = 0;
        HttpSession session = request.getSession(); // 对于CSRF,这里会获取新的Cookie
        User user = (User) session.getAttribute("user");
        if (user != null) {
            uid = user.getUid();
        }

        // 有CSRF代码
        int count = evaluateService.add(iid, uid, content);
        log.warn("添加评论: " + count);

        // 使用token解决CSRF
        /*String requestToken = params.get("token");
        Object token = session.getAttribute("token");

        if (Objects.equals(token, requestToken)) {
            int count = evaluateService.add(iid, uid, content);
            log.warn(token + ", 添加评论: " + count);
        } else {
            log.error("token不对,被CSRF攻击了! 解决CSRF!");
        }*/
    }
}
